package org.siberia.server.model;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Query;
import javax.persistence.Transient;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;

import com.google.gwt.user.client.rpc.IsSerializable;

@Entity
public class Action
{
	@Id
	@Column(name = "id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long id;

	/** title */
	@NotNull
	public String title;
	
	/** start time */
	@NotNull
	public Date startDate;
	
	/** end time */
	@NotNull
	public Date endDate;
	
	/** all day long */
	public Boolean allDayLong;
	
	/** remark */
	public String remark;
	
	/** version */
	@Version
	public Integer version;
	
	/** link to an action suite */
	@JoinColumn
	public Long actionSuiteKey;
	
	@Transient
	private ActionSuite actionSuite;
	
	@NotNull
	public int dayOffset = 0;

	public static EntityManager entityManager()
	{
		return EMF.get().createEntityManager();
	}
	
	public ActionSuite getActionSuite()
	{
		if ( this.actionSuiteKey == null )
		{
			this.actionSuite = ActionSuite.findActionSuite(this.actionSuiteKey);
		}
		return this.actionSuite;
	}
	
	public static List<Action> findActionsForSuite(Long _actionSuiteKey)
	{
		List<Action> actions = null;
		
		EntityManager manager = entityManager();
		
		try
		{
			Query query = manager.createQuery("select o from Action o where o.actionSuiteKey=:actionSuiteKey");
			query.setParameter("actionSuiteKey", _actionSuiteKey);
			actions = query.getResultList();
		}
		finally
		{
			manager.close();
		}
		
		return actions;
	}
	
	public void persist()
	{
		EntityManager manager = entityManager();
		try
		{	manager.persist(this); }
		finally
		{	manager.close(); }
	}
	
	public static void deleteAll()
	{
		EntityManager manager = entityManager();
		
		try
		{
			Query query = manager.createQuery("DELETE from Action o");
			query.executeUpdate();
		}
		finally
		{	manager.close(); }
	}
}
